/**
 * 主屏幕组件 - 学习首页
 * 显示课程列表、用户进度、连续学习天数等信息
 * 包含课程解锁逻辑和进度跟踪功能
 * 使用最原始简洁的设计，更加人性化和符合用户习惯
 */
import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
  Alert,
  RefreshControl
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { Ionicons } from '@expo/vector-icons';
import * as Progress from 'react-native-progress';
import { SafeAreaView } from 'react-native-safe-area-context';

import { lessonsData } from '../data/lessons';
import { 
  getUserProgress, 
  getLessonsProgress, 
  initializeUserProgress,
  getStudyStats
} from '../utils/storage';
import { 
  AppCard, 
  StatusIndicator, 
  LoadingIndicator, 
  EmptyState,
  Tag
} from '../components/CommonUI';
import { NumberUtils, DateUtils } from '../utils/CommonUtils';
import { AppHeader } from '../components/Headers';
import { 
  UserProgressCard, 
  LessonCard, 
  BottomTip 
} from '../components/ScreenComponents';

const { width } = Dimensions.get('window');

/**
 * 主屏幕组件
 * @param {Object} navigation - React Navigation 导航对象
 */
export default function HomeScreen({ navigation }) {
  // 组件状态定义
  const [userProgress, setUserProgress] = useState({
    totalXP: 0,
    currentStreak: 0,
    level: 1,
    lessonsCompleted: 0,
    totalLessons: lessonsData.length
  });
  const [lessonsProgress, setLessonsProgress] = useState({});
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false); // 下拉刷新状态
  const [studyStats, setStudyStats] = useState(null); // 学习统计

  // 组件初始化时加载数据
  useEffect(() => {
    loadUserData();
  }, []);

  // 页面获得焦点时刷新数据
  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      loadUserData();
    });
    return unsubscribe;
  }, [navigation]);

  /**
   * 加载用户数据的主函数
   * 包括用户进度、课程进度和学习统计
   */
  const loadUserData = async () => {
    try {
      setLoading(true);
      
      // 初始化用户进度（如果是首次使用）
      await initializeUserProgress();
      
      // 并行加载数据以提高性能
      const [progress, lessonsProg, stats] = await Promise.all([
        getUserProgress(),
        getLessonsProgress(),
        getStudyStats()
      ]);
      
      setUserProgress(progress);
      setLessonsProgress(lessonsProg);
      setStudyStats(stats);
      
      console.log('用户数据加载成功');
    } catch (error) {
      console.error('加载用户数据失败:', error);
      Alert.alert('加载失败', '无法加载你的学习进度，请检查网络连接后重试');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };



  /**
   * 下拉刷新回调函数
   */
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    loadUserData();
  }, []);

  /**
   * 检查课程是否解锁
   * 第一个课程始终解锁，其他课程需要前一个课程完成
   * @param {number} lessonIndex - 课程索引
   * @returns {boolean} 是否解锁
   */
  const isLessonUnlocked = (lessonIndex) => {
    if (lessonIndex === 0) return true; // 第一个课程始终解锁
    
    // 检查前一个课程是否完成
    const previousLessonId = lessonsData[lessonIndex - 1].id;
    return lessonsProgress[previousLessonId]?.completed || false;
  };

  /**
   * 获取课程状态
   * @param {Object} lesson - 课程对象
   * @returns {string} 课程状态：'completed' | 'available' | 'locked'
   */
  const getLessonStatus = (lesson) => {
    if (lessonsProgress[lesson.id]?.completed) {
      return 'completed';
    }
    
    const lessonIndex = lessonsData.findIndex(l => l.id === lesson.id);
    if (isLessonUnlocked(lessonIndex)) {
      return 'available';
    }
    
    return 'locked';
  };

  /**
   * 处理课程点击事件
   * @param {Object} lesson - 被点击的课程
   */
  const handleLessonPress = (lesson) => {
    const status = getLessonStatus(lesson);
    
    if (status === 'locked') {
      Alert.alert(
        '课程尚未解锁',
        '请先完成前一个课程来解锁这个课程！',
        [{ text: '好的', style: 'default' }]
      );
      return;
    }

    // 导航到课程页面
    navigation.navigate('Lesson', { 
      lessonId: lesson.id, 
      lessonTitle: lesson.title 
    });
  };

  /**
   * 渲染课程卡片组件
   * 使用新的LessonCard组件来显示课程信息
   * @param {Object} lesson - 课程数据
   * @param {number} index - 课程索引
   * @returns {JSX.Element} 课程卡片组件
   */
  const renderLessonCard = (lesson, index) => {
    const status = getLessonStatus(lesson);
    const progressData = lessonsProgress[lesson.id];
    
    return (
      <LessonCard
        key={lesson.id}
        lesson={lesson}
        index={index}
        status={status}
        progressData={progressData}
        onPress={() => handleLessonPress(lesson)}
      />
    );
  };

  // 加载中状态
  if (loading) {
    return (
      <SafeAreaView style={styles.loadingContainer}>
        <LoadingIndicator text="加载中..." />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="light" backgroundColor="#58CC02" />
      
      {/* 使用新的AppHeader组件 */}
      <AppHeader 
        title="英语学习"
        userStats={{
          currentStreak: userProgress.currentStreak,
          totalXP: userProgress.totalXP
        }}
        showStats={true}
      />

      {/* 课程列表 - 修复滚动遮挡问题 */}
      <ScrollView 
        style={styles.lessonsContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#58CC02']}
            tintColor="#58CC02"
            title="下拉刷新"
            titleColor="#58CC02"
          />
        }
      >
        {/* 使用新的UserProgressCard组件 */}
        <UserProgressCard 
          userProgress={userProgress}
          username="学习者"
        />
        
        <Text style={styles.sectionTitle}>你的课程</Text>
        
        {lessonsData.map((lesson, index) => renderLessonCard(lesson, index))}
        
        {/* 使用新的BottomTip组件 */}
        <BottomTip text="💡 每天坚持学习15分钟，连续打卡可获得更多奖励！" />
        
        {/* 添加底部间距，避免内容被Tab Bar遮挡 */}
        <View style={styles.bottomSpacing} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  
  // 简洁原始的Header设计
  header: {
    backgroundColor: '#58CC02',
    paddingHorizontal: 20,
    paddingVertical: 15,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
  },
  headerStats: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  statItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 16,
  },
  statText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
    marginLeft: 4,
  },
  
  // 用户信息卡片 - 调整边距，避免遮挡
  userCard: {
    backgroundColor: '#fff',
    marginHorizontal: 0,
    marginTop: 20,
    marginBottom: 16,
    borderRadius: 16,
    padding: 18,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  userInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  avatarContainer: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: '#E8F5E8',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  userDetails: {
    flex: 1,
  },
  userName: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    marginBottom: 2,
  },
  levelText: {
    fontSize: 14,
    color: '#666',
  },
  progressContainer: {
    marginTop: 12,
  },
  progressHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  progressInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  progressLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
    marginLeft: 6,
  },
  progressText: {
    fontSize: 13,
    color: '#58CC02',
    fontWeight: '600',
  },
  progressBarContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  progressPercentage: {
    fontSize: 12,
    color: '#666',
    fontWeight: '500',
    marginLeft: 8,
    minWidth: 35,
    textAlign: 'right',
  },
  motivationText: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center',
    fontStyle: 'italic',
    lineHeight: 16,
  },
  
  // 快速统计样式
  quickStats: {
    alignItems: 'center',
  },
  quickStatItem: {
    alignItems: 'center',
    backgroundColor: '#FFF8DC',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 12,
    minWidth: 50,
  },
  quickStatNumber: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#FF9500',
  },
  quickStatLabel: {
    fontSize: 10,
    color: '#B8860B',
    fontWeight: '500',
  },
  
  // 课程列表 - 修复样式，移除固定高度
  lessonsContainer: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 0,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 16,
    marginTop: 8,
    paddingHorizontal: 0,
  },
  lessonCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 18,
    marginBottom: 12,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.08,
    shadowRadius: 2,
    borderWidth: 1,
    borderColor: '#f0f0f0',
  },
  completedCard: {
    backgroundColor: '#E8F5E8',
    borderColor: '#58CC02',
    borderWidth: 2,
  },
  lockedCard: {
    backgroundColor: '#f8f8f8',
    opacity: 0.6,
  },
  lessonHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  lessonIcon: {
    width: 48,
    height: 48,
    borderRadius: 12,
    backgroundColor: '#58CC02',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  completedIcon: {
    backgroundColor: '#4CAF50',
  },
  lockedIcon: {
    backgroundColor: '#ccc',
  },
  lessonNumber: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
  lessonInfo: {
    flex: 1,
  },
  lessonTitle: {
    fontSize: 17,
    fontWeight: '600',
    color: '#333',
    marginBottom: 4,
  },
  lessonDescription: {
    fontSize: 13,
    color: '#666',
    lineHeight: 18,
  },
  lockedText: {
    color: '#999',
  },
  lessonMeta: {
    alignItems: 'flex-end',
  },
  xpBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFF8DC',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 10,
    marginBottom: 5,
  },
  xpText: {
    marginLeft: 4,
    fontSize: 12,
    fontWeight: 'bold',
    color: '#B8860B',
  },
  difficultyText: {
    fontSize: 12,
    color: '#666',
    fontStyle: 'italic',
  },
  bottomTip: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    backgroundColor: '#E8F5E8',
    padding: 16,
    borderRadius: 12,
    marginTop: 24,
    marginBottom: 8,
  },
  tipText: {
    flex: 1,
    marginLeft: 12,
    fontSize: 14,
    color: '#2E7D2E',
    lineHeight: 20,
  },
  
  // 添加底部间距，避免内容被Tab Bar遮挡 - 优化用户体验
  bottomSpacing: {
    height: 20,
  },
  
  // 加载状态样式
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
  },
  loadingText: {
    marginTop: 12,
    fontSize: 16,
    color: '#666',
  },
  
  // 尝试次数信息样式 - 提升用户体验
  attemptInfo: {
    fontSize: 12,
    color: '#999',
    marginTop: 4,
    fontStyle: 'italic',
  },
});